import AddOrderProductCard from '@/components/AddOrderProductCard';
import OrderDetailModal from '@/components/OrderDetailModal';
import { getRestaurantAreas, getRestaurantTables } from '@/services/ant-design-pro/desk';
import { getProductCategory, getProductList } from '@/services/ant-design-pro/product';
import { createTrade, previewTradePrice, printTradeTicket } from '@/services/order';
import { BulbTwoTone } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import {
  AutoComplete,
  Button,
  Card,
  Col,
  Divider,
  Empty,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  Spin,
  Switch,
  Tabs,
  Tag,
} from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { history } from '@umijs/max';

const { Option } = Select;

enum DeskStatus {
  Free = '空闲',
  Occupied = '就餐中',
}

const data = [
  {
    key: '1',
    name: 'Craft Beer A',
    sku: '大杯',
    price: '￥50',
    quantity: 1,
  },
  {
    key: '2',
    name: 'Craft Beer B',
    sku: '小杯',
    price: '￥60',
    quantity: 1,
  },
  {
    key: '3',
    name: 'Craft Beer C',
    sku: '大杯',
    price: '￥70',
    quantity: 1,
  },
];

const DeskList: React.FC = () => {
  const [checkoutModalOpen, setCheckoutModalOpen] = useState(false);
  const [deskDetailOpen, setDeskDetailOpen] = useState(false);
  const [orderProductOpen, setOrderProductOpen] = useState(false);

  const [deskDetail, setDeskDetail] = useState(null);
  const [selectedItems, setSelectedItems] = useState([]);
  const [tableList, setTableList] = useState([]);
  const [tableAreaList, setTableAreaList] = useState([]);
  const [areaList, setAreaList] = useState([]);
  const [productList, setProductList] = useState([]);
  const [productCollection, setProductCollection] = useState([]);
  const [productDetail, setProductDetail] = useState(null);
  const [orderParams, setOrderParams] = useState({});
  const [tradeOrderItem, setTradeOrderItem] = useState({});
  const [orderDiscountPreview, setOrderDiscountPreview] = useState({});
  const [currentOrderId, setCurrentOrderId] = useState(null);
  const [currentUpdateTime, setCurrentUpdateTime] = useState(+new Date());
  const [loading, setLoading] = useState(false);

  const orderForm = Form.useForm()[0];

  const desks = [
    { id: 1, name: '1号桌', status: DeskStatus.Occupied, money: 100 },
    { id: 2, name: '2号桌', status: DeskStatus.Free, money: 0 },
    { id: 3, name: '3号桌', status: DeskStatus.Occupied, money: 200 },
    { id: 4, name: '4号桌', status: DeskStatus.Free, money: 0 },
    { id: 5, name: '5号桌', status: DeskStatus.Occupied, money: 300 },
    { id: 6, name: '6号桌', status: DeskStatus.Free, money: 0 },
  ];

  const getStatusTag = (status: DeskStatus) => {
    switch (status) {
      case DeskStatus.Free:
        return <Tag color="green">{status}</Tag>;
      case DeskStatus.Occupied:
        return <Tag color="red">{status}</Tag>;
      default:
        return null;
    }
  };

  const handleDesk = (data) => {
    setDeskDetailOpen(true);
    setDeskDetail(data);
  };

  const handleQuantityChange = (key, value) => {
    setSelectedItems((prevItems) =>
      prevItems.map((item) => (item.key === key ? { ...item, quantity: value } : item)),
    );
  };

  const handleAddItem = (item) => {
    setSelectedItems((prevItems) => {
      const existingItem = prevItems.find((i) => i.key === item.key && i.sku === item.sku);
      if (existingItem) {
        return prevItems.map((i) =>
          i.key === item.key && i.sku === item.sku
            ? { ...i, quantity: i.quantity + item.quantity }
            : i,
        );
      } else {
        return [...prevItems, item];
      }
    });
  };

  const ProductColumns = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
      render: (_, record) => (
        <Select
          defaultValue={record.sku}
          style={{ width: 120 }}
          onChange={(value) => (record.sku = value)}
        >
          <Option value="大杯">大杯</Option>
          <Option value="小杯">小杯</Option>
        </Select>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      render: (_, record) => (
        <InputNumber
          size="large"
          min={1}
          defaultValue={1}
          onChange={(value) => (record.quantity = value)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="primary" onClick={() => handleAddItem(record)}>
          添加
        </Button>
      ),
    },
  ];

  const ProductShowColumns = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
  ];

  const initTable = async (areaId = undefined) => {
    setLoading(true);
    const resp = await getRestaurantTables({ areaId, page: 1, pageSize: 50 });

    const { list } = resp?.data;
    const listByArea = [];
    list.forEach((item) => {
      const areaIndex = listByArea.findIndex((_) => _?.area === item.area);
      console.log('[areaIndex]', areaIndex);
      if (areaIndex === -1) {
        listByArea.push({
          area: item.area,
          tables: [item],
        });
      } else {
        listByArea[areaIndex].tables.push(item);
      }
    });
    console.log('[listByArea]', listByArea);
    setTableAreaList(listByArea);
    setTableList(list);
    setLoading(false);
    setCurrentUpdateTime(+new Date());
  };

  const initArea = async () => {
    const resp = await getRestaurantAreas({ page: 1, pageSize: 50 });

    const { list } = resp?.data;

    setAreaList(list);
  };

  const initProductList = async (params = {}) => {
    const resp = await getProductList({ ...params, status: 1, page: 1, pageSize: 50 });

    const { list } = resp?.data;

    setProductList(list);
  };

  const handleTabClick = (tab) => {
    if (tab === 'all') {
      initTable();
    } else {
      initTable(tab);
    }
  };

  const handleOrder = (tableId) => {
    setOrderProductOpen(true);
    setOrderParams({
      channel: 'minipro',
      restaurantId: window.MERCHANT_ID,
      tableId,
    });
  };

  const initProductCollection = async () => {
    const resp = await getProductCategory({ page: 1, pageSize: 50 });
    const { list } = resp?.data;
    setProductCollection(list);
  };

  const handleCreateTrade = async () => {
    orderForm.validateFields().then(async () => {
      const resp = await createTrade(orderParams);
      if (resp?.code === 0) {
        message.success('创建成功');
        setOrderParams({});
        setOrderProductOpen(false);
        console.log('😈resp', resp);
        const orderId = resp?.data?.id;
        console.log('😈orderId', orderId);
        // Modal.confirm({
        //   title: '是否需要打印制作小票',
        //   onOk: async () => {
        //     console.log('打印小票');
        //     const resp = await printTradeTicket(orderId);
        //     if (resp.code === 0) {
        //       message.success('操作成功');
        //     }
        //   },
        // });


        if (localStorage.getItem('disableOrderPrint') !== 'true') {
          const resp2 = await printTradeTicket(orderId);
          if (resp2.code === 0) {
            message.success('打印成功');
          }
        }
        initTable();
      }
    });
  };

  const handleProductPreviewPrice = async (tradeOrderList) => {
    const resp = await previewTradePrice({ ...orderParams, tradeOrderList });
    console.log('[resp]', resp);
    setOrderDiscountPreview(resp?.data);
  };

  const initInter = () => {
    initArea();
    initTable();
  };

  useEffect(() => {
    initInter();
    const inter = setInterval(() => {
      initInter();
    }, 60000);

    initProductList();
    initProductCollection();

    return () => {
      clearInterval(inter);
    };
  }, []);

  return (
    <>
      <Modal
        zIndex={9995}
        width={'90vw'}
        height={'90vh'}
        centered
        title="点单"
        destroyOnClose
        open={orderProductOpen}
        onCancel={() => setOrderProductOpen(false)}
        onOk={() => {
          handleCreateTrade();
          orderForm.resetFields();
        }}
      >
        <AddOrderProductCard
          defaultProductList={productList}
          onChange={
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            (tradeOrderList) => {
              console.log('[tradeOrderList]', tradeOrderList);
              setOrderParams({
                ...orderParams,
                tradeOrderList,
              });
            }
          }
        ></AddOrderProductCard>

        <Card title="基础信息" className="mt10">
          <Form
            form={orderForm}
            onValuesChange={(changedValues, allValues) =>
              setOrderParams({ ...orderParams, ...allValues })
            }
            labelCol={{
              span: '2',
            }}
          >
            {/* <Form.Item label="人数" name="seats">
              <InputNumber></InputNumber>
            </Form.Item> */}

            <Form.Item label="备注" name={'remark'}>
              <Input.TextArea></Input.TextArea>
            </Form.Item>
          </Form>
        </Card>
      </Modal>

      <Modal
        title="结账"
        open={checkoutModalOpen}
        onCancel={() => {
          setCheckoutModalOpen(false);
        }}
        zIndex={101}
      >
        <Card title="会员信息">
          <AutoComplete placeholder="请输入会员手机号搜索" className="w100"></AutoComplete>
          <Row className="mt20">
            <Col span={24}>
              <Row justify="space-between">
                <Col>余额：</Col>
                <Col>￥180</Col>
              </Row>
              <Row justify="space-between" className="mt10">
                <Col>积分</Col>
                <Col>2000</Col>
              </Row>
            </Col>
          </Row>
        </Card>

        <Card title="订单折扣" className="mt20">
          <Form layout="vertical">
            <Form.Item label="使用会员积分抵扣">
              <Switch></Switch>
            </Form.Item>
            <Form.Item label="使用会员余额抵扣">
              <Switch defaultChecked={true}></Switch>
            </Form.Item>
          </Form>
        </Card>

        <Row className="mt20">
          <Col span={24}>
            <Row justify="space-between">
              <Col>折扣列表：</Col>
            </Row>
            <Row justify="space-between">
              <Col>整单折扣:</Col>
              <Col>9折</Col>
            </Row>
            <Row justify="space-between">
              <Col>折扣金额：</Col>
              <Col>-￥180</Col>
            </Row>

            <Divider></Divider>

            <Row justify="space-between">
              <Col>总计金额：</Col>
              <Col>￥180</Col>
            </Row>
          </Col>
        </Row>
      </Modal>

      <OrderDetailModal
        orderId={currentOrderId}
        onCancel={() => {
          setCurrentOrderId(null);
          initTable();
        }}
      ></OrderDetailModal>

      <PageContainer>
        <Card>
          <Tabs
            onTabClick={handleTabClick}
            tabBarExtraContent={
              <div className="bold">
                <BulbTwoTone className="mr5" /> 最新更新时间：
                {moment(currentUpdateTime).format('HH:mm:ss')}
              </div>
            }
          >
            <Tabs.TabPane key={'all'} tab={'全部'}>
              <Spin spinning={loading}>
                <Row gutter={[10, 10]}>
                  {tableAreaList.map((tableArea) => {
                    return (
                      <div key={tableArea.area} className="w100 mb10">
                        <h3 className="bold">【{tableArea.area}】</h3>
                        <Row gutter={[10, 10]}>
                          {tableArea?.tables?.map((desk) => {
                            return (
                              <Col span={6} key={desk.id}>
                                <Card
                                  key={desk.id}
                                  title={desk.name}
                                  hoverable
                                  onClick={(e) => {
                                    if (desk?.processingTrade) {
                                      history.push(`/order/detail/${desk?.processingTrade}`);
                                    } else {
                                      e.stopPropagation();
                                      history.push(`/order/new?tableId=${desk.id}`);
                                    }
                                  }}
                                >
                                  {desk?.processingTrade && (
                                    <h3 className="bold text-center red">有未完结订单</h3>
                                  )}

                                  {!desk?.processingTrade && (
                                    <h3 className="bold text-center ">空闲</h3>
                                  )}
                                </Card>
                              </Col>
                            );
                          })}
                        </Row>
                      </div>
                    );
                  })}
                </Row>
              </Spin>
            </Tabs.TabPane>
            {areaList.map((item) => {
              return (
                <Tabs.TabPane key={item.id} tab={item.name}>
                  <Row gutter={[10, 10]}>
                    {tableList.map((desk) => (
                      <Col span={6} key={desk.id}>
                        <Card
                          key={desk.id}
                          title={desk.name}
                          hoverable
                          onClick={(e) => {
                            if (desk?.processingTrade) {
                              e.stopPropagation();
                              setCurrentOrderId(desk?.processingTrade);
                            } else {
                              e.stopPropagation();
                              history.push(`/order/new?tableId=${desk.id}`);
                            }
                          }}
                        >
                          {desk?.processingTrade && (
                            <h3 className="bold text-center red">有未完结订单</h3>
                          )}

                          {!desk?.processingTrade && <h3 className="bold text-center ">空闲</h3>}
                        </Card>
                      </Col>
                    ))}
                  </Row>
                </Tabs.TabPane>
              );
            })}
          </Tabs>

          {tableList?.length === 0 && <Empty></Empty>}
        </Card>
      </PageContainer>
    </>
  );
};

export default DeskList;
